package cn.wowjoy.office.data.remote;

import android.os.RemoteException;

import io.reactivex.BackpressureStrategy;
import io.reactivex.Flowable;
import io.reactivex.FlowableEmitter;
import io.reactivex.FlowableOnSubscribe;
import io.reactivex.Observable;
import io.reactivex.functions.Function;

/**
 * Created by Sherily on 2017/10/9.
 * * Description: rx flatMap for parse remote data
 */

public class ResultDataParse<T> implements Function<ResultWrapper<T>, Flowable<T>> {

    @SuppressWarnings("unchecked")
    @Override
    public Flowable<T> apply(ResultWrapper<T> tResultWrapper) throws Exception {
        return Flowable.create(new FlowableOnSubscribe<T>() {
            @Override
            public void subscribe(FlowableEmitter<T> e) throws Exception {
                if (tResultWrapper.isSuccess()){
                    if (null == tResultWrapper.getData())
                        e.onNext((T)ResultEmpty.EMPTY);
                    else
                        e.onNext(tResultWrapper.getData());
                    e.onComplete();

                } else {
                    e.onError(new ResultException(tResultWrapper.getReturnMsg(),tResultWrapper.getReturnCode()));
                }

            }
        }, BackpressureStrategy.BUFFER);
    }
}
